package com.jdd.modules.parking.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.*;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.system.vo.LoginUser;
import com.jdd.common.util.CacheUtil;
import com.jdd.common.util.SnowFlakeUtil;
import com.jdd.modules.parking.entity.ConfigParkInfo;
import com.jdd.modules.parking.mapper.ConfigParkInfoMapper;
import com.jdd.modules.parking.service.IConfigParkInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

/**
 * @Description: 车场临时车、月租车过期配置
 * @Author: jdd
 * @Date: 2021-02-18
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "车场临时车、月租车过期配置")
@RestController
@RequestMapping("/parking/configParkInfo")
public class ConfigParkInfoController {
    @Resource
    private IConfigParkInfoService configParkInfoService;
    @Resource
    private ConfigParkInfoMapper configParkInfoMapper;
    @Resource
    private CacheUtil cacheUtil;
    /**
     * 修改车场的车位数
     *
     * @param configParkInfo 接收车场的识别参数信息配置
     * @return 返回操作结果信息
     * @Author: lcy（修改）
     */
    @AutoLog(value = "修改车场的车位数-编辑")
    @ApiOperation(value = "修改车场的车位数-编辑", notes = "修改车场的车位数-编辑")
    @PutMapping(value = "/editTemporary")
    @OperationLogDetail(detail ="修改车场的车位数，编辑",level= LogLevelType.ONE,operationType = OperationType.UPDATE,operationUnit = OperationUnit.UNKNOWN)
    public Result<ConfigParkInfo> editTemporary(@RequestBody ConfigParkInfo configParkInfo) {
        Result<ConfigParkInfo> result = new Result<>();
        ConfigParkInfo configParkInfoEntity = configParkInfoService.findConfigParkInfoByParkCode();
        if (configParkInfoEntity == null) {
            result.error500("未找到对应实体或车位数不正确");
        } else {
           if(ObjectUtil.isEmpty(configParkInfo.getTemporaryParking())){
               result.error500("车位数量输入不正确");
           }else{
               Integer integer = configParkInfoMapper.updateTemporaryParking(configParkInfoEntity.getId(), configParkInfo.getTemporaryParking());
               if (integer>0) {
                   //删除configParkInfoService.findConfigParkInfoByParkCode的缓存
                   cacheUtil.delete("ConfigParkInfo","getConfigParkInfo");
                   result.success("修改成功!");
               } else {
                   result.success("修改失败!");
               }
           }
        }
        return result;
    }

    /**
     * 分页列表查询
     * @param configParkInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     * @Author: liushengnan（修改，加入权限控制）
     */
    @AutoLog(value = "车场临时车、月租车过期配置-分页列表查询")
    @ApiOperation(value = "车场临时车、月租车过期配置-分页列表查询", notes = "车场临时车、月租车过期配置-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ConfigParkInfo>> queryPageList(ConfigParkInfo configParkInfo,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       String startTime, String endTime,
                                                       HttpServletRequest req) {
        Result<IPage<ConfigParkInfo>> result = new Result<IPage<ConfigParkInfo>>();
        QueryWrapper<ConfigParkInfo> queryWrapper = QueryGenerator.initQueryWrapper(configParkInfo, req.getParameterMap());
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            queryWrapper.and(wrapper -> wrapper.ge("create_time", startTime + " 00:00:00").le("create_time", endTime + " 23:59:59"));
        }
        Page<ConfigParkInfo> page = new Page<>(pageNo, pageSize);
        IPage<ConfigParkInfo> pageList = configParkInfoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * @param map 携带了parkCode
     * @return 返回当前车场的识别参数信息配置对象，如果该对象为null表示当前车场还未进行识别参数配置
     * @Author: liushengnan（创建）
     */
    @AutoLog(value = "车场临时车、月租车过期配置-查询车场识别参数配置信息")
    @ApiOperation(value = "车场临时车、月租车过期配置-查询车场识别参数配置信息", notes = "车场临时车、月租车过期配置-查询车场识别参数配置信息")
    @PostMapping(value = "/queryOne")
    public Result<ConfigParkInfo> queryOne(@RequestBody Map<String, Object> map) {
        Result<ConfigParkInfo> result = new Result<>();
        try {
            ConfigParkInfo configParkInfo = configParkInfoService.findConfigParkInfoByParkCode();
            result.setResult(configParkInfo);
            result.success("查询成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 添加车场的识别参数信息
     * @param configParkInfo 识别参数信息配置对象
     * @return 返回操作结果信息
     * @Author: liushengnan（修改）
     */
    @AutoLog(value = "车场临时车、月租车过期配置-配置车场的识别参数信息")
    @ApiOperation(value = "车场临时车、月租车过期配置-配置车场的识别参数信息", notes = "车场临时车、月租车过期配置-配置车场的识别参数信息")
    @PostMapping(value = "/add")
    @OperationLogDetail(detail ="车场临时车、月租车过期配置，添加",level= LogLevelType.ONE,operationType = OperationType.INSERT,operationUnit = OperationUnit.UNKNOWN)
    public Result<ConfigParkInfo> add(@RequestBody ConfigParkInfo configParkInfo) {
        Result<ConfigParkInfo> result = new Result<>();
        try {
            LoginUser sysUser =
                    (LoginUser) SecurityUtils.getSubject().getPrincipal();
            configParkInfo.setCreateUser(sysUser.getUsername());
            configParkInfo.setId(SnowFlakeUtil.getId());
            configParkInfoService.saveEntity(configParkInfo);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 修改车场的识别参数信息配置
     *
     * @param configParkInfo 接收车场的识别参数信息配置
     * @return 返回操作结果信息
     * @Author: liushengnan（修改）
     */
    @AutoLog(value = "车场临时车、月租车过期配置-编辑")
    @ApiOperation(value = "车场临时车、月租车过期配置-编辑", notes = "车场临时车、月租车过期配置-编辑")
    @PutMapping(value = "/edit")
    @OperationLogDetail(detail ="车场临时车、月租车过期配置，编辑",level= LogLevelType.ONE,operationType = OperationType.UPDATE,operationUnit = OperationUnit.UNKNOWN)
    public Result<ConfigParkInfo> edit(@RequestBody ConfigParkInfo configParkInfo) {
        Result<ConfigParkInfo> result = new Result<>();
        ConfigParkInfo configParkInfoEntity = configParkInfoService.findConfigParkInfoById(configParkInfo.getId());
        if (configParkInfoEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = configParkInfoService.updateEntity(configParkInfo);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            } else {
                result.success("修改失败!");
            }
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车场临时车、月租车过期配置-通过id删除")
    @ApiOperation(value = "车场临时车、月租车过期配置-通过id删除", notes = "车场临时车、月租车过期配置-通过id删除")
    @DeleteMapping(value = "/delete")
    @OperationLogDetail(detail ="车场临时车、月租车过期配置，通过id删除",level= LogLevelType.ONE,operationType = OperationType.DELETE,operationUnit = OperationUnit.UNKNOWN)
    public Result<?> delete(@RequestParam(name = "invateuserdetailId", required = true) String id) {
        try {
            configParkInfoService.deleteEntityById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "车场临时车、月租车过期配置-批量删除")
    @ApiOperation(value = "车场临时车、月租车过期配置-批量删除", notes = "车场临时车、月租车过期配置-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @OperationLogDetail(detail ="车场临时车、月租车过期配置，批量删除",level= LogLevelType.ONE,operationType = OperationType.DELETE,operationUnit = OperationUnit.UNKNOWN)
    public Result<ConfigParkInfo> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<ConfigParkInfo> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.configParkInfoService.deleteEntityByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车场临时车、月租车过期配置-通过id查询")
    @ApiOperation(value = "车场临时车、月租车过期配置-通过id查询", notes = "车场临时车、月租车过期配置-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ConfigParkInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<ConfigParkInfo> result = new Result<>();
        ConfigParkInfo configParkInfo = configParkInfoService.findConfigParkInfoById(id);
        if (configParkInfo == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(configParkInfo);
            result.setSuccess(true);
        }
        return result;
    }
}
